package com.swotplus.admin.web.weixin;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.swotplus.admin.web.weixin.util.WxUtil;
import com.swotplus.common.constant.Constants;
import com.swotplus.system.weixin.entity.WxcmsAccount;
import com.swotplus.system.weixin.service.WxcmsAccountService;
import com.swotplus.system.weixin.vo.Matchrule;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.menu.WxMpMenu;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.swotplus.common.core.AjaxResult;
import com.swotplus.framework.web.BaseController;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.beans.factory.annotation.Autowired;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import com.swotplus.system.weixin.service.WxcmsAccountMenuService;
import java.util.*;
import com.swotplus.system.weixin.entity.WxcmsAccountMenu;
import com.swotplus.system.weixin.service.WxcmsAccountMenuService;
import org.springframework.stereotype.Controller;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author hugang
 * @since 2020-06-04
 */
@Controller
@RequestMapping("/wxcmsAccountMenu")
public class WxcmsAccountMenuController extends BaseController {

    private String prefix = "/weixin/menu";


    @Autowired
    private WxcmsAccountMenuService wxcmsAccountMenuService;
    @Autowired
    private WxcmsAccountService wxcmsAccountService;

    @Autowired
    private WxMpService wxMpService;

    @RequestMapping("/list")
    @RequiresPermissions("wxcmsAccountMenu:view")
    public String toHtml(){

        return prefix + "/menu";
    }


    /**
     * 选择资源
     * @return
     */
    @RequestMapping("/addmsg")
    @RequiresPermissions("wxcmsAccountMenu:view")
    public String toAddMsgHtml(){
        return prefix + "/template/msg";
    }

    @RequestMapping("/listData")
    @RequiresPermissions("wxcmsAccountMenu:list")
    @ResponseBody
    public AjaxResult listData(WxcmsAccountMenu wxcmsAccountMenu){
        try
        {
            List<WxcmsAccountMenu> menus=wxcmsAccountMenuService.list();
            Matchrule matchrule = new Matchrule();
            return AjaxResult.success(WxUtil.prepareMenus(menus, matchrule));
        } catch (Exception e)
        {
            return AjaxResult.warn(e.getMessage());
        }

    }

    /**
     * 保存菜单
     * @param menus
     * @return
     */
    @RequestMapping(value = "/save")
    @ResponseBody
    public AjaxResult save(String menus) {
        JSONArray jsons = JSONArray.parseArray(menus);
        //每次先行删除公众号所有菜单
        wxcmsAccountMenuService.remove(null);
        if (CollectionUtils.isNotEmpty(jsons)) {
            for (int i = 0; i < jsons.size(); i++) {
                JSONObject json = jsons.getJSONObject(i);
                if (null != json) {
                    WxcmsAccountMenu accountMenu = new WxcmsAccountMenu();
                    accountMenu.setName(json.getString("name"));
                    accountMenu.setSort(i + 1);
                    accountMenu.setParentId(0);
                    if (json.containsKey("type")) {
                        accountMenu.setMtype(json.getString("type"));
                        //判断是否设置key
                        if (Constants.MENU_NEED_KEY.contains(json.getString("type"))) {
                            accountMenu.setEventType("fix");
                            accountMenu.setMsgType(json.getString("msgType"));
                            accountMenu.setMsgId(json.getString("msgId"));
                        }
                    }
                    if (json.containsKey("url")) {
                        accountMenu.setUrl(json.getString("url"));
                    }
                    if (json.containsKey("media_id")) {
                        accountMenu.setMsgId(json.getString("media_id"));
                    }
                    accountMenu.setCreateTime(LocalDateTime.now());
                    //保存
                    wxcmsAccountMenuService.save(accountMenu);
                    //判断是否有subbutton
                    if (json.containsKey("sub_button")) {
                        JSONArray buttons = json.getJSONArray("sub_button");
                        if (CollectionUtils.isNotEmpty(buttons)) {
                            Integer pid = accountMenu.getId();
                            for (int j = 0; j < buttons.size(); j++) {
                                json = buttons.getJSONObject(j);
                                accountMenu = new WxcmsAccountMenu();
                                accountMenu.setParentId(pid);
                                accountMenu.setName(json.getString("name"));
                                accountMenu.setSort(j + 1);
                                if (json.containsKey("type")) {
                                    accountMenu.setMtype(json.getString("type"));
                                    //判断是否设置key
                                    if (Constants.MENU_NEED_KEY.contains(json.getString("type"))) {
                                        accountMenu.setEventType("fix");
                                        accountMenu.setMsgType(json.getString("msgType"));
                                        accountMenu.setMsgId(json.getString("msgId"));
                                    }
                                }
                                if (json.containsKey("url")) {
                                    accountMenu.setUrl(json.getString("url"));
                                }
                                if (json.containsKey("media_id")) {
                                    accountMenu.setMsgId(json.getString("media_id"));
                                }
                                accountMenu.setCreateTime(LocalDateTime.now());
                                wxcmsAccountMenuService.save(accountMenu);
                            }
                        }
                    }
                }
            }
        }
        return AjaxResult.success();
    }


    //创建微信公众账号菜单 Api
    @RequestMapping(value = "/doPublishMenu")
    @ResponseBody
    public AjaxResult doPublishMenu()  throws WxErrorException {
        WxcmsAccount  wxcmsAccount=wxcmsAccountService.getById("1");
        if(wxcmsAccount!=null){
            List<WxcmsAccountMenu> menus=wxcmsAccountMenuService.list();
            JSONObject json= WxUtil.prepareMenus(menus,new Matchrule());
            String result=wxMpService.switchoverTo(wxcmsAccount.getAppid()).getMenuService().menuCreate(json.toString());
            return  AjaxResult.success(result);
        }
        return AjaxResult.error();
    }


    /**
     * 获取微信公众号菜单 Api
     * @param appid
     * @return
     * @throws WxErrorException
     */
    @GetMapping("/get")
    @ResponseBody
    public WxMpMenu menuGet( String appid) throws WxErrorException {
        return this.wxMpService.switchoverTo(appid).getMenuService().menuGet();
    }
}

